$(function(){
  // get elem
  let $url     = $('input[type="text"]'),
      $btnSave = $('input[type="button"]'),
      $img     = $('img'),
      $tmpImg  = $('<img>');
  
  // load localStorage image
  loadImage()
  // load tmp image
  
  $btnSave.click(() => {
    $tmpImg.attr('crossOrigin','anonymous');

    // validate url: not empty,pattern
    $tmpImg.attr('src', $url.val());
    $url.val('');
  });
  $tmpImg.load(function() {
    var can = $('<canvas>').get(0);
    var ctx = can.getContext('2d');

    ctx.width = this.width;
    ctx.height = this.height
  
    // file tmp image canvas
    ctx.drawImage(this, 0, 0, can.width, can.height);
    
    // canvas output base64
    // save base64 localStorage
    localStorage.setItem('img', can.toDataURL());
    loadImage() 
  });

  function loadImage() {
    let strImg = localStorage['img'];
    if(strImg) {
      $img.attr('src', strImg);
      $img.css({display: 'block'})
    } else {
    $img.css({display: 'none'})
    }
  }
});
